package Servlet;

import Dao.Impl.VerificationCodeDAOImpl;
import Dao.VerificationCodeDAO;
import Service.EmailService;
import entity.VerificationCode;
import org.json.JSONException;
import org.json.JSONObject;
import utils.DBUtil;
import utils.EmailUtil;
import utils.VerificationCodeUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author Su
 * @Date 2025/4/30 10:14
 * @Version 1.0 （版本号）
 */
// VerificationCodeServlet.java
@WebServlet("/api/verification-code/send")
public class VerificationCodeServlet extends HttpServlet {
    // 声明DAO和服务类实例
    private VerificationCodeDAO verificationCodeDAO;// 验证码数据访问对象
    private EmailService emailService; // 邮件服务实例


    // 初始化方法 - Servlet生命周期中只执行一次
    @Override
    public void init() throws ServletException {
        super.init();// 调用父类初始化
        try {
            Connection connection = DBUtil. getConnection();
            // 初始化验证码DAO和邮件服务
            this.verificationCodeDAO = new VerificationCodeDAOImpl(connection);
            this.emailService = new EmailService(connection);
        } catch (SQLException e) {
            throw new ServletException("初始化数据库连接失败", e);
        }
    }

    // 处理POST请求的方法
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // 设置响应类型为json
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");

        // 从请求参数中获取邮箱和验证码类型
        String email = req.getParameter("email");
        String type = req.getParameter("type"); // "register" 或 "reset-password"

        // 创建响应JSON对象
        JSONObject responseJson = new JSONObject();

        if (email == null || email.trim().isEmpty()) {
            responseJson.put("code", 400);
            responseJson.put("message", "邮箱不能为空");
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            resp.getWriter().print(responseJson.toString());
        } else {
            try {
                // 1、生成验证码并发送
                Map<String, Object> map = emailService.codeGenAndSend(email, type);
                System.out.println("map数据：" + map.toString());//调试日志
                // 2、发送结果
                if (map.get("code").equals("500")) {//失败
                    resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                }else{//成功
                    responseJson.put("code", map.get("code"));
                    responseJson.put("message", map.get("message"));
                    resp.setStatus(HttpServletResponse.SC_OK);
                }
            } catch (SQLException e) {
                e.printStackTrace();
                responseJson.put("code", 500);
                responseJson.put("message", "数据库执行错误，请重试");
                resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            } catch (Exception e) {
                e.printStackTrace();
                responseJson.put("code", 500);
                responseJson.put("message", "服务器内部错误");
                resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            } finally {
                resp.getWriter().print(responseJson.toString());
            }//业务逻辑封装在EmailService中
            //Servlet只负责请求/响应处理和流程控制
        }
    }
}
